<template>
  <div>
    <el-form ref="ruleForm" class="demo-ruleForm">
      <div class="top-box">
        <div class="caseNum">用工人数： {{employedNum}} / {{requireNum}}</div>
        <el-button type="primary" @click="reloadAssignList()" size="mini">刷新</el-button>
      </div>
      <el-table
        ref="assignTable"
        v-loading="loading"
        border
        :data="tableData.data"
        @selection-change="onSelectTab"
        style="width: 100%"
      >
<!--         row-key="getRowKeys" @select="handleCheckBox" @select-all="handleSelectAll"-->
        <el-table-column
          align="center"
          type="selection"
          :selectable="selectable"
          width="40"
          v-if="processStatus===1"
        />
        <el-table-column
          label="头像" width="60" align="center">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                style="width: 36px; height: 36px"
                :src="scope.row.user.avatar"
                :preview-src-list="[scope.row.user.avatar]"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="真实姓名"
          width="110"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{scope.row.user.name | filterEmpty  }} | {{scope.row.user.sex | sexFilterForWork}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="手机号"
          width="110"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{scope.row.user.phone_number | filterEmpty}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="求职信息"
          min-width="150"
        >
          <template slot-scope="scope">
            <template v-if="scope.row.userInfo">
              <p class="overHiddenOne">想找{{scope.row.userInfo.intention | filterEmpty}} | {{scope.row.userInfo.free_text | filterEmpty}}有空 | {{scope.row.userInfo.education_text | filterEmpty}}学历 | {{scope.row.userInfo.experience_text | filterEmpty}}经验</p>
              <p class="overHiddenOne" v-if="scope.row.userInfo.skill_label_text" >技能标签：<el-tag size="small" type="info" v-for="(item, index) in scope.row.userInfo.skill_label_text" :key="index" class="mr5">{{ item }}</el-tag></p>
            </template>
            <template v-else>-</template>
          </template>
        </el-table-column>
        <el-table-column
          label="评分"
          width="55"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.total_score === 0 ? '暂无' : scope.row.total_score }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          width="55"
          align="center"
        >
          <template slot-scope="scope">
            <span :class="scope.row.is_employed===1?'fontGreen':''">{{scope.row.is_employed | isEmployFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="145" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="primary" @click="onDetails(scope.row.user_id)" size="mini">详情</el-button>
            <el-button type="danger" @click="cancelAssign(scope.row.id)" size="mini" style="margin-left:5px;" v-if="scope.row.is_employed === 1 && processStatus===1">取消</el-button>
            <el-button type="success" @click="commentAssign(scope.row)" size="mini" style="margin-left:5px;" v-if="scope.row.is_employed === 1 && processStatus===2" v-hasPermi="['admin:work:comment']">评价</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-sizes="[7]"
        :page-size="robFrom.limit"
        :current-page="robFrom.page"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total"
        @size-change="handleSizeChange"
        @current-change="pageChange"
      />
      <el-form-item style="margin:20px 0 0 0;"  v-if="processStatus===1">
        <el-button type="primary" @click="submitForm" v-hasPermi="['admin:work:assign']">确定派遣</el-button>
        <el-button @click="resetForm">取消</el-button>
      </el-form-item>
    </el-form>
    <!--详情-->
    <el-dialog
      title="求职工详情"
      :close-on-click-modal="false"
      :visible.sync="Visible"
      :append-to-body= "true"
      width="1100px"
    >
      <user-details ref="userDetails" :id="rob_user_id" v-if="Visible" @close="close"></user-details>
    </el-dialog>
    <!--评价-->
    <el-dialog
      title="求职工评价"
      :close-on-click-modal="false"
      :visible.sync="visible"
      :append-to-body= "true"
      width="600px"
    >
      <comment-from v-if="visible" :id="rob_id" :editData="editData" @resetCommentForm="resetCommentForm"></comment-from>
    </el-dialog>
  </div>

</template>

<script>
  import { getApplyApi,assignApplyApi,cancelAssign,getEmployedNumApi } from '@/api/workApi'
  import {Debounce} from '@/utils/validate'
  import userDetails from '@/views/user/list/userDetails'
  import * as categoryApi from '@/api/categoryApi'
  import commentFrom from '@/views/work/editComment'
  export default {
    name: "WorkEditAssign",
    components:{ userDetails,commentFrom },
    filters: {
      sexFilterForWork(status) {
        const statusMap = {
          0: '未知',
          1: '男',
          2: '女',
        }
        return statusMap[status]
      },
      isEmployFilter(status) {
        const statusMap = {
          0: '未知',
          1: '已选',
          2: '-',
        }
        return statusMap[status]
      }
    },
    props:{
      id: {
        type: Number,
        default: null
      },
      requireNum:{
        type: Number,
        default: 0
      },
      processStatus:{
        type: Number,
        default: 0
      }
    },
    data() {
      return {
        tableData: {
          data: [],
          total: 0
        },
        robFrom: {
          work_id: 0,
          is_employed: 0,//此处查全部，已派遣的无法再选择
          page: 1,
          limit: 7,
        },
        loading: false,

        idKey:'id',
        selectedData: [],
        selectionList: [],
        multipleSelectionAll: [],
        robIds: '',//选中记录id，逗号分隔
        employedNum:0,

        //求职工
        rob_user_id: null,
        Visible: false,
        //评价
        rob_id:null,
        visible: false,
        editData: {},
      }
    },
    mounted() {
      if(this.id) {
        this.workRobList()
        this.getIsEmployedNum()
      }
    },
    methods: {
      // 用户详情
      onDetails(id){
        this.rob_user_id = id
        this.Visible = true
      },
      close() {
        this.Visible = false
        //this.workRobList()
      },

      //刷新求职工列表
      reloadAssignList(){
        this.workRobList()
        this.getIsEmployedNum()
      },

      workRobList() {
        this.loading = true

        this.robFrom.work_id = this.id
        getApplyApi(this.robFrom).then(res => {
          this.tableData.data = res.list
          this.tableData.total = res.count

          this.$nextTick(function() {
            this.setSelectRow()// 调用跨页选中方法
          })
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },
      getIsEmployedNum() {
        getEmployedNumApi({work_id:this.id,is_employed:1}).then(res => {
          this.employedNum = res
        })
      },

      pageChange(page) {
        this.changePageCoreRecordData()
        this.robFrom.page = page
        this.workRobList()
      },
      handleSizeChange(val) {
        this.changePageCoreRecordData()
        this.robFrom.limit = val
        this.workRobList()
      },

      submitForm:Debounce(function(formName) {
        let data = [];
        if(!this.robIds){
          if(this.multipleSelectionAll.length === 0){
            this.$message.error("请勾选要派遣的人员")
            return
          }
          this.multipleSelectionAll.map((item) => {
            data.push(item.id)
          });
          /*if (data.length > this.requireNum){
            this.$message.error("要派遣的人员不可超过用工人数，当前选择人数："+data.length)
            return
          }*/
          this.robIds = data.join(',');
        }else{
          data = this.robIds.split(',')
          if(data.length === 0){
            this.$message.error("请勾选要派遣的人员")
            return
          }
          /*if (data.length > this.requireNum){
            this.$message.error("要派遣的人员不可超过用工人数，当前选择人数："+data.length)
            return
          }*/
        }

        //console.log(this.robIds);return false;
        const _pram = {
          ids:this.robIds,
          work_id:this.id
        }
        //console.log(_pram);return false;
        assignApplyApi(_pram).then(async res => {
          this.$message.success('派遣成功')
          this.$parent.$parent.visibleAssign = false
          this.$parent.$parent.getList()
        })
      }),

      //取消
      cancelAssign(id) {
        this.$confirm('确定取消吗?').then(() => {
          cancelAssign(id).then(data => {
            this.workRobList()
            this.getIsEmployedNum()
            this.$message.success('取消成功')
          })
        })
      },

      //评价
      commentAssign(editData) {
        this.rob_id = editData.id
        this.editData = editData
        this.visible = true
      },
      resetCommentForm(){
        this.visible = false;
      },

      //设置已派遣的无法再选择
      selectable: function(row, index) {
        if(row.is_employed !== 1){
          return true;
        }
        return false;
      },
      // 全选
      onSelectTab (selection) {
        this.selectionList = selection;
        setTimeout(() => {
          this.changePageCoreRecordData()
          let data = [];
          if(this.multipleSelectionAll.length){
            this.multipleSelectionAll.map((item) => {
              data.push(item.id)
            });
            this.robIds = data.join(',');
          }
        }, 50)
      },
      // 设置选中的方法
      setSelectRow() {
        if (!this.multipleSelectionAll || this.multipleSelectionAll.length <= 0) {
          return
        }
        // 标识当前行的唯一键的名称
        const idKey = this.idKey
        const selectAllIds = []
        this.multipleSelectionAll.forEach(row => {
          selectAllIds.push(row[idKey])
        })

        this.$refs.assignTable.clearSelection()
        for (var i = 0; i < this.tableData.data.length; i++) {
          if (selectAllIds.indexOf(this.tableData.data[i][idKey]) >= 0) {
            // 设置选中，记住table组件需要使用ref="table"
            this.$refs.assignTable.toggleRowSelection(this.tableData.data[i], true)
          }
        }
      },
      // 记忆选择核心方法
      changePageCoreRecordData() {
        // 标识当前行的唯一键的名称
        const idKey = this.idKey
        const that = this
        // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
        if (this.multipleSelectionAll.length <= 0) {
          this.multipleSelectionAll = this.selectionList
          return
        }
        // 总选择里面的key集合
        const selectAllIds = []
        this.multipleSelectionAll.forEach(row => {
          selectAllIds.push(row[idKey])
        })
        const selectIds = []
        // 获取当前页选中的id
        this.selectionList.forEach(row => {
          selectIds.push(row[idKey])
          // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
          if (selectAllIds.indexOf(row[idKey]) < 0) {
            that.multipleSelectionAll.push(row)
          }
        })
        const noSelectIds = []
        // 得到当前页没有选中的id
        this.tableData.data.forEach(row => {
          if (selectIds.indexOf(row[idKey]) < 0) {
            noSelectIds.push(row[idKey])
          }
        })
        noSelectIds.forEach(uid => {
          if (selectAllIds.indexOf(uid) >= 0) {
            for (let i = 0; i < that.multipleSelectionAll.length; i++) {
              if (that.multipleSelectionAll[i][idKey] == uid) {
                // 如果总选择中有未被选中的，那么就删除这条
                that.multipleSelectionAll.splice(i, 1)
                break
              }
            }
          }
        })
      },

      resetForm() {
        this.selectedData= []
        this.selectionList= []
        this.multipleSelectionAll = []
        this.robIds = ''
        this.employedNum = 0
        this.$refs.assignTable.clearSelection()
        this.$emit('resetAssignForm');
      },
    }
  }
</script>

<style scoped>
 .selWidth{
   width: 90%;
 }
 .overHiddenOne{
   overflow: hidden;white-space: nowrap;text-overflow: ellipsis;
 }
 .caseNum{
   font-weight:bold;
 }
 .fontGreen{
   color:#1BBE6B;
 }
 .top-box{
   display:flex;
   justify-content: space-between;
   align-items: center;
   margin-bottom:10px;
 }
</style>
